package emulator.shell.GUI.symbols;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;

import emulator.assembler.SymbolTable;
import emulator.assembler.SymbolTableEntry;
import emulator.assembler.SymbolTableSource;
import emulator.shell.DebugShell;
import emulator.shell.GUI.debugger.CodePanel;

public class SymbolTablePresenter
{
	private SymbolTableView view;
	private String appName;
	private CodePanel codePanel;
	
	public SymbolTablePresenter(String appName, CodePanel codePanel)
	{
		this.appName = appName;
		this.codePanel = codePanel;
	}
	
	public void toggleView()
	{
		if (view == null)
		{
			view = new SymbolTableView(appName, this);
			view.initView(createViewModel());
			view.restorePosition();
			view.setVisible(true);
		}
		else
		{
			view.toFront();
		}
	}

	private SymbolTableVM createViewModel()
	{
		SymbolTableVM viewModel = new SymbolTableVM();
		SymbolTable symbolTable = codePanel.getSymbolTable();
		for (SymbolTableEntry entry : symbolTable.getSymbols())
		{
			viewModel.addSymbol(entry);
		}
		return viewModel;
	}

	public void showCode(int address)
	{
		if (codePanel != null)
			codePanel.showCode(address, true);
	}
	
	public void onCloseView()
	{
		view = null;
	}

	public void closeView()
	{
		if (view != null)
		{
			view.setVisible(false);
			view = null;
		}
	}

	public void loadSymbols(String symbolFileName)
	{
		codePanel.loadSymbols(symbolFileName);
		view.updateViewModel(createViewModel());
	}

	public void saveSymbols(String fileName, Collection<SymbolTableSource> selectedSources)
	{
		FileOutputStream file = null;
		try
		{
			file = new FileOutputStream(fileName);
			codePanel.getSymbolTable().save(file, selectedSources);
		}
		catch (IOException e)
		{
			DebugShell.getInstance().getErr().println("File write failed for \""+fileName+"\" (symbols): "+e.getMessage());
		}
		finally
		{
			if (file != null)
				try { file.close(); } catch (IOException e) {}
		}
		
	}

	public void deleteSymbols(Collection<SymbolTableSource> selectedSources)
	{
		codePanel.getSymbolTable().delete(selectedSources);
		view.updateViewModel(createViewModel());
	}
}
